package top.anka1.fxgui;

import javafx.event.ActionEvent;
import javafx.scene.control.*;
import top.anka1.ims.*;

import javafx.fxml.FXML;
import javafx.stage.Stage;
/**
 * AddIngredientController is a controller class for adding ingredients to the restaurant's inventory.
 * It handles the user interface and input validation for adding new ingredients.
 * @author Anka
 */
public class AddIngredientController {
    private RestaurantGUI restaurantGUI;
    @FXML
    private TextField ingredientNameField;
    @FXML
    private TextField ingredientPriceField;

    public void setData(RestaurantGUI restaurantGUI) {
        this.restaurantGUI = restaurantGUI;
    }
    private void showError(Stage stage, String title, String HeaderText, String contentText) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.initOwner(stage);
        alert.setTitle(title);
        alert.setHeaderText(HeaderText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }

    @FXML
    public void submit(ActionEvent event) {
        String ingredientName = ingredientNameField.getText();
        Double ingredientPrice = null;
        Boolean flag = true;
        try {
            ingredientPrice = Double.parseDouble(ingredientPriceField.getText());
            if (ingredientPrice < 0) {
                flag = false;
                throw new NumberFormatException("Price cannot be negative");
            }
        } catch (Exception e) {
            flag = false;
            showError((Stage) ingredientNameField.getScene().getWindow(), "Input Error", "Invalid Price. Please enter a valid price.", "Error: " + e.getMessage());
        }
        if (flag) {
            restaurantGUI.getRestaurantService().addIngredient(ingredientName, ingredientPrice);
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Success");
            alert.setHeaderText("Ingredient Added");
            alert.setContentText("Ingredient " + ingredientName + " has been added successfully.");
            alert.showAndWait();
        }
    }
}
